/**
 * @class   Ext.ux.FilterTree
 * 在树状菜单中加了过滤器、全展开按钮和全收缩按钮
 */
Ext.ux.FilterTree = function(config){
    config.tbar=new Ext.Toolbar({
                cls:'top-toolbar',
                items:[
                new Ext.form.TextField({
                    id:'search',
                    margins : '0 0 0 0',
                    width: 200,
                    emptyText:'输入过滤关键字',
                    listeners:{
                        render: this.textFieldRender.createDelegate(this)
                    }
                }),'-',
                {
                    iconCls: 'icon-expand-all',
                    tooltip: '全部展开',
                    handler: this.expand.createDelegate(this)
                }, '-', {
                    iconCls: 'icon-collapse-all',
                    tooltip: '全部收缩',
                    handler: this.collapse.createDelegate(this)
                }]
            });
    Ext.ux.FilterTree.superclass.constructor.call(this,config);
    //设置树的过滤器
    this.filter = new Ext.tree.TreeFilter(this, {
        clearBlank: true,
        autoClear: true
    });
    this.hiddenPkgs = new Array;
}
Ext.extend(Ext.ux.FilterTree, Ext.tree.TreePanel, {
    /**
     * 过滤树函数
     */
    filterTree: function(e){
        var text = e.target.value;
        Ext.each(this.hiddenPkgs, function(n){
            n.ui.show();
        },this);
        if(!text){
            this.filter.clear();
            return;
        }
        this.expandAll();
        
        var re = new RegExp( Ext.escapeRe(text), 'i');
        this.filter.filterBy(function(n){
            
            return !n.isLeaf()||re.test(n.text);
        });
        
        // hide empty packages that weren't filtered
        this.hiddenPkgs = [];
        this.root.cascade(function(n){
             if(!n.isLeaf() && this.hasChild(n,re)==false){
                n.ui.hide();
                this.hiddenPkgs.push(n);
            }
        },this);
    },
    hasChild:function(n,re){
        var str=false;
        n.cascade(function(n1){
            if(re.test(n1.text)){
                         str=true;
                         return;
                 }
             });
         return str;
    },
    expand:function(){
        this.root.expand(true); 
    },
    collapse:function(){
        this.root.collapse(true); 
    },
    textFieldRender:function(f){
        f.el.on('keydown', this.filterTree.createDelegate(this), f, {buffer: 350});
    }
});